/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dataentry;

import com.mysql.jdbc.ResultSetMetaData;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author i.capurro
 */
public class SaveChanges {
    
    private String url = "jdbc:mysql://localhost/data_entry";
    private String user = "root";
    private String password = "";
    private HashMap edit = null;
    private List del = null;
    private String tName = null;

    public SaveChanges(String tName, HashMap edit, List del) {
        this.edit = edit;
        this.del = del;
        this.tName = tName;
    }
    
    public void save() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection c = DriverManager.getConnection(url, user, password);
        
        Iterator ite = edit.values().iterator();
        
        while (ite.hasNext()) {
            Statement stmt = c.createStatement();
            EditValues aux = (EditValues) ite.next();
            String sql = "UPDATE " + tName + " SET ";
            
            Iterator itv = aux.getValues().iterator();
            Value v = (Value) itv.next();
            
            sql = sql + v.getCol() + "=" + v.getValue();
            while (itv.hasNext()) {
                v = (Value) itv.next();
                sql = sql + "," + v.getCol() + "=" + v.getValue();
            }
            sql = sql + " WHERE id=" + aux.getId();
            stmt.executeUpdate(sql);
        }
        
        Iterator itd = del.iterator();
        
        while (itd.hasNext()) {
            Statement stmt = c.createStatement();
            String aux = Integer.toString((Integer)itd.next());
            String sql = "DELETE FROM  " + tName + " WHERE id=" + aux;
            stmt.execute(sql);
        }
        c.close();
    }
}
